package com.hx.portal.controller.user;




import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.client.utils.StringUtils;
import com.hx.common.exception.CustomerException;
import com.hx.common.result.Result;
import com.hx.hospital.pojo.User;
import com.hx.hospital.service.UserService;
import com.hx.portal.dot.WxLoginDto;
import com.hx.portal.utils.WXBizDataCrypt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import io.swagger.annotations.Authorization;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

import static io.netty.handler.codec.stomp.StompHeaders.LOGIN;

@RequestMapping("/user")
@RestController
@ResponseBody
@Api(description = "登录相关接口文档")
@Slf4j
public class UserController {


    @Reference
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    //个人小程序账号无法获取手机号码，所以此功能无法实现
    @PostMapping(value = "/wx/get/phone")
    @ApiOperation(value = "微信解密手机号码",notes = "微信解密手机号码",httpMethod = "POST",authorizations = {@Authorization(value = "token")})
    public Result getPhoneNumber(String encryptedData, String iv, String token) throws CustomerException {
        User user = userService.queryUserByToken(token);
        log.info("user:{}",user);
        String result= WXBizDataCrypt.decrypt1(encryptedData,user.getSessionKey(),iv);
        JSONObject json= JSONObject.parseObject(result);

        Map<String,Object> map=new HashMap<>();
        if (!StringUtils.isEmpty(result)&&result.length()>0) {
            map.put("purePhoneNumber", json.getString("purePhoneNumber"));
            map.put("phoneNumber", json.getString("phoneNumber"));
            //保存用户手机号码到服务器
            return new Result(map);
        }
        return new Result();
    }

    @PostMapping(value = "/wx/login")
    @ApiOperation(value = "微信登录",notes = "微信登录",httpMethod = "POST")
    public Result wxLogin2(@RequestBody WxLoginDto WxLoginDto) throws CustomerException {
        Map<String, String> result = userService.wxLogin(WxLoginDto.getCode());
        return new Result(result);
    }


    @PostMapping(value = "/query")
    @ApiOperation(value = "查询登录信息",notes = "查询登录信息",httpMethod = "POST")
    public Result query( String token) throws CustomerException {
        User user = userService.queryUserByToken(token);
        return new Result();
    }

    @PostMapping(value = "/logout")
    @ApiOperation(value = "登出",notes = "登出",httpMethod = "POST")
    public Result logout( String token){
        redisTemplate.delete(LOGIN+token);
        return new Result();
    }

}
